'use client';

import React, { useState } from 'react';
import {
  ProofRecord,
  BatchInfo,
  submitProofStorage,
  waitForProofConfirmation,
  generateBusinessEvidence,
  getCommonEvidenceContent,
  formatErrorMessage,
  isNetworkError,
} from '@/utils/storage';
import { useServerStatus, useBatchOperation } from '@/hooks/common';
import {
  PageHeader,
  ServerStatusIndicator,
  StatsCard,
  ProgressBar,
  StatusBadge,
  Card,
  Button,
  InputGroup,
} from '@/components/common';
import { LICAI_ROLLUP_URL } from '@/utils/config';

const STORAGE_BASE_URL = LICAI_ROLLUP_URL;

export default function Home() {
  const { serverRunning, recheckServer } = useServerStatus(`${STORAGE_BASE_URL}/proof/status?hash=test`);
  const batchOperation = useBatchOperation<ProofRecord>();
  
  const [proofCount, setProofCount] = useState<number>(10);
  const [proofs, setProofs] = useState<ProofRecord[]>([]);
  const [batches, setBatches] = useState<BatchInfo[]>([]);

  // 提交单个随机存证
  const submitRandomProof = async () => {
    const evidence = getCommonEvidenceContent();
    
    try {
      const result = await submitProofStorage(evidence, STORAGE_BASE_URL);
      
      const newProof: ProofRecord = {
        hash: result.hashs[0],
        evidence: evidence,
        status: 'pending',
        timestamp: Date.now(),
      };

      setProofs(prev => [newProof, ...prev]);

      // 异步等待确认
      waitForProofConfirmation(result.hashs[0], (status) => {
        setProofs(prev => 
          prev.map(proof => 
            proof.hash === result.hashs[0] 
              ? { ...proof, status }
              : proof
          )
        );
      }, 5, 3000, STORAGE_BASE_URL);

    } catch (error) {
      console.error('提交存证失败:', error);
      
      if (isNetworkError(error)) {
        alert('网络连接失败，请检查存证服务器是否运行在 http://localhost:9084');
        return;
      }
      
      alert(`提交存证失败: ${formatErrorMessage(error)}`);
    }
  };

  // 批量生成存证测试
  const generateBatchProofs = async () => {
    if (!serverRunning) {
      alert('存证服务器未运行，请先启动存证服务');
      return;
    }

    batchOperation.startBatch();
    setProofs([]);

    try {
      for (let i = 0; i < proofCount; i++) {
        const evidence = generateBusinessEvidence();
        
        try {
          const result = await submitProofStorage(evidence, STORAGE_BASE_URL);
          
          const proofRecord: ProofRecord = {
            hash: result.hashs[0],
            evidence: evidence,
            status: 'pending',
            timestamp: Date.now(),
          };

          batchOperation.addItem(proofRecord);
          setProofs(prev => [proofRecord, ...prev]);

          // 异步等待确认
          waitForProofConfirmation(result.hashs[0], (status) => {
            setProofs(prev => 
              prev.map(proof => 
                proof.hash === result.hashs[0] 
                  ? { ...proof, status }
                  : proof
              )
            );
          }, 5, 3000, STORAGE_BASE_URL);

          // 添加延迟避免过快发送
          await new Promise(resolve => setTimeout(resolve, 100));

        } catch (error) {
          console.error(`提交存证 ${i + 1} 失败:`, error);
          
          const failedProof: ProofRecord = {
            hash: `failed-${Date.now()}-${i}`,
            evidence: evidence,
            status: 'failed',
            timestamp: Date.now(),
          };

          batchOperation.addItem(failedProof);
          setProofs(prev => [failedProof, ...prev]);
        }
        
        batchOperation.updateProgress(i + 1);
      }

    } catch (error) {
      console.error('批量存证生成失败:', error);
      alert('批量存证生成失败，请检查控制台错误信息');
    } finally {
      batchOperation.completeBatch();
    }
  };

  const confirmedCount = proofs.filter(p => p.status === 'confirmed').length;
  const pendingCount = proofs.filter(p => p.status === 'pending').length;
  const failedCount = proofs.filter(p => p.status === 'failed').length;

  return (
    <div className="min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]">
      <PageHeader title="理财Rollup演示" />

      <main className="flex flex-col gap-8 items-center w-full max-w-5xl mx-auto pt-20">
        
        {/* 服务器状态 */}
        <div className="w-full bg-gray-50 rounded-lg p-6">
          <h2 className="text-xl font-semibold mb-4">存证系统状态</h2>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <ServerStatusIndicator 
              running={serverRunning} 
              onRecheck={recheckServer} 
            />
            <div>
              <span className="font-medium">已确认存证: </span>
              <span className="text-green-600 font-semibold">{confirmedCount}</span>
            </div>
            <div>
              <span className="font-medium">批次数量: </span>
              <span className="text-blue-600 font-semibold">{batches.length} 个批次</span>
            </div>
          </div>
        </div>

        {/* 单个存证提交 */}
        <Card title="提交单个存证">
          <div className="flex items-center gap-4">
            <span className="text-gray-600">自动生成理财业务相关的存证内容</span>
            <Button
              onClick={submitRandomProof}
              disabled={!serverRunning || batchOperation.isRunning}
            >
              提交随机存证
            </Button>
          </div>
        </Card>

        {/* 批量测试配置 */}
        {batchOperation.step === 'setup' && (
          <Card title="批量存证测试">
            <InputGroup
              label="存证数量"
              value={proofCount.toString()}
              onChange={(value: string) => setProofCount(Number(value))}
              type="number"
              min={1}
              max={100}
              className="mb-4"
            />
            <span className="text-sm text-gray-600 block mb-4">模拟理财业务高频存证场景</span>
            
            <Button
              onClick={generateBatchProofs}
              disabled={!serverRunning || batchOperation.isRunning}
              variant="success"
            >
              {batchOperation.isRunning ? '生成中...' : '开始批量测试'}
            </Button>
          </Card>
        )}

        {/* 测试进度 */}
        {batchOperation.step !== 'setup' && (
          <Card title="存证状态统计">
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-4">
              <StatsCard value={proofs.length} label="总存证数" color="blue" />
              <StatsCard value={confirmedCount} label="已确认" color="green" />
              <StatsCard value={pendingCount} label="等待确认" color="yellow" />
              <StatsCard value={failedCount} label="失败" color="red" />
            </div>
            
            {batchOperation.step === 'running' && (
              <ProgressBar
                progress={batchOperation.progress}
                label={`已提交 ${proofs.length} / ${proofCount} 个存证`}
                color="bg-green-600"
              />
            )}

            {batchOperation.step === 'completed' && (
              <Button
                onClick={() => {
                  batchOperation.resetBatch();
                  setProofs([]);
                  setBatches([]);
                }}
                variant="secondary"
              >
                重新开始测试
              </Button>
            )}
          </Card>
        )}

        {/* 存证记录 */}
        {proofs.length > 0 && (
          <Card title="存证记录">
            <div className="max-h-96 overflow-y-auto">
              <table className="w-full text-sm">
                <thead className="sticky top-0 bg-gray-100">
                  <tr>
                    <th className="border px-2 py-2">存证哈希</th>
                    <th className="border px-2 py-2">存证内容</th>
                    <th className="border px-2 py-2">提交时间</th>
                    <th className="border px-2 py-2">状态</th>
                  </tr>
                </thead>
                <tbody>
                  {proofs.map((proof) => (
                    <tr key={proof.hash}>
                      <td className="border px-2 py-1 font-mono text-xs">
                        {proof.hash.slice(0, 16)}...
                      </td>
                      <td className="border px-2 py-1 max-w-xs break-words">
                        {proof.evidence}
                      </td>
                      <td className="border px-2 py-1 text-xs">
                        {new Date(proof.timestamp).toLocaleString()}
                      </td>
                      <td className="border px-2 py-1">
                        <StatusBadge status={proof.status} />
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </Card>
        )}

        {/* ZK-Rollup 批次信息 */}
        {batches.length > 0 && (
          <Card title="ZK-Rollup 批次状态">
            <div className="mb-4 text-sm text-gray-600">
              ZK-Rollup将多个理财存证打包成批次，生成零知识证明后提交到主链，实现高吞吐量和低成本
            </div>
            
            <div className="space-y-4">
              {batches.slice().reverse().map((batch) => (
                <div key={batch.id} className="border rounded-lg p-4 bg-blue-50">
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div>
                      <div className="font-medium text-blue-600">批次 ID</div>
                      <div className="text-xs font-mono text-gray-600">{batch.id}</div>
                    </div>
                    <div>
                      <div className="font-medium">包含存证数量</div>
                      <div className="text-lg font-semibold text-green-600">{batch.proofsCount} 个</div>
                    </div>
                    <div>
                      <div className="font-medium">批次状态</div>
                      <div className={`inline-flex items-center ${
                        batch.status === 'confirmed' ? 'text-green-600' : 'text-yellow-600'
                      }`}>
                        <StatusBadge status={batch.status} />
                      </div>
                    </div>
                  </div>
                  
                  {batch.merkleRoot && (
                    <div className="mt-3 pt-3 border-t border-blue-200">
                      <div className="text-sm">
                        <div><span className="font-medium">Merkle根:</span> <span className="font-mono text-xs">{batch.merkleRoot.slice(0, 32)}...</span></div>
                        <div><span className="font-medium">打包时间:</span> {new Date(batch.timestamp).toLocaleString()}</div>
                      </div>
                    </div>
                  )}
                </div>
              ))}
            </div>
          </Card>
        )}

      </main>
    </div>
  );
}
